package com.xbp.examsystem.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbp.examsystem.entity.*;
import com.xbp.examsystem.exception.ExamException;
import com.xbp.examsystem.mapper.*;
import com.xbp.examsystem.service.AIService;
import com.xbp.examsystem.service.QuestionService;
import com.xbp.examsystem.utils.ExcelUtil;
import com.xbp.examsystem.vo.AiGenerateRequestVo;
import com.xbp.examsystem.vo.QuestionImportVo;
import com.xbp.examsystem.vo.QuestionQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题目Service实现类
 * 实现题目相关的业务逻辑
 */
@Slf4j
@Service
@Transactional
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    @Autowired
    private QuestionAnswerMapper questionAnswerMapper;

    @Autowired
    private QuestionChoiceMapper questionChoiceMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;
    @Autowired
    private AIService aiService;

    @Override
    public void getPageByStream(Page<Question> pageParam, QuestionQueryVo questionQueryVo) {
        Long categoryId = questionQueryVo.getCategoryId();
        String difficulty = questionQueryVo.getDifficulty();
        String type = questionQueryVo.getType();
        String keyword = questionQueryVo.getKeyword();
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(keyword), Question::getTitle, keyword);
        queryWrapper.eq(StringUtils.hasLength(type), Question::getType, type);
        queryWrapper.eq(StringUtils.hasLength(difficulty), Question::getDifficulty, difficulty);
        queryWrapper.eq(categoryId != null, Question::getCategoryId, categoryId);
        queryWrapper.orderByDesc(Question::getCreateTime);
        baseMapper.selectPage(pageParam, queryWrapper);
        List<Question> records = pageParam.getRecords();
        setAnswersAndChoice(records);
    }

    private void setAnswersAndChoice(List<Question> records) {
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> questionIds = records.stream().map(Question::getId).collect(Collectors.toList());
            List<QuestionAnswer> questionAnswers = questionAnswerMapper.selectList(new LambdaQueryWrapper<QuestionAnswer>().in(QuestionAnswer::getQuestionId, questionIds));
            List<QuestionChoice> questionChoices = questionChoiceMapper.selectList(new LambdaQueryWrapper<QuestionChoice>().in(QuestionChoice::getQuestionId, questionIds));
            Map<Long, QuestionAnswer> questionAnswersMap = questionAnswers.stream().collect(Collectors.toMap(
                            QuestionAnswer::getQuestionId,
                            questionAnswer -> questionAnswer
                    )
            );
            Map<Long, List<QuestionChoice>> questionChoicesMap = questionChoices.stream().collect(Collectors.groupingBy(QuestionChoice::getQuestionId));

            records.forEach(question -> {
                Long questionId = question.getId();
                QuestionAnswer questionAnswer = questionAnswersMap.get(questionId);
                question.setAnswer(questionAnswer);

                if (question.getType().equals("CHOICE")) {
                    List<QuestionChoice> questionChoices1 = questionChoicesMap.get(questionId);
                    if (!CollectionUtils.isEmpty(questionChoices1)) {
                        questionChoices1.sort(Comparator.comparingInt(QuestionChoice::getSort));
                        question.setChoices(questionChoices1);
                    }
                }
            });


        }
    }

    @Override
    public Question getQuestionDetailsById(Long id) {

        //根据id获取题目详情
        Question questionDetailsById = baseMapper.getQuestionDetailsById(id);
        //启动一个线程往Redis中存放热门题目
        new Thread(() -> {
            try {
                //使用ZSet数据类型向Redis中存放热门题目
                redisTemplate.opsForZSet().incrementScore("question:popular", id, 1);
            } catch (Exception e) {
                // Redis连接失败，记录日志
                log.warn("Redis连接失败，无法更新热门题目: {}", e.getMessage());
            }
        }).start();
        return questionDetailsById;

    }

    @Override
    public void addQuestion(Question question) {
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        questionLambdaQueryWrapper.eq(Question::getTitle, question.getTitle());
        questionLambdaQueryWrapper.eq(Question::getCategoryId, question.getCategoryId());
        questionLambdaQueryWrapper.eq(Question::getType, question.getType());
        boolean b = baseMapper.exists(questionLambdaQueryWrapper);
        if (b) {
            //获取分类名
            Category category = categoryMapper.selectById(question.getCategoryId());
            //在某个分类下该类型的题目已经存在同名的题目
            throw new ExamException(567, "在<" + category.getName() + ">分类下已经存在名字为 '" + question.getTitle() + "' 的题目");
        }
        //1.调用自带的方法插入题目信息
        baseMapper.insert(question);
        Long id = question.getId();
        QuestionAnswer answer = question.getAnswer();
        answer.setQuestionId(id);
        if (question.getType().equals("CHOICE")) {
            List<QuestionChoice> choices = question.getChoices();
            if (!CollectionUtils.isEmpty(choices)) {
                // 按照sort属性排序选项
                choices.sort(Comparator.comparingInt(QuestionChoice::getSort));
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < choices.size(); i++) {
                    QuestionChoice questionChoice = choices.get(i);
                    questionChoice.setQuestionId(id);
                    questionChoice.setSort(i);
                    if (questionChoice.getIsCorrect()) {
                        if (stringBuilder.length() > 0) {
                            stringBuilder.append(",");
                        }
                        stringBuilder.append((char) (i + 65));
                    }
                    questionChoiceMapper.insert(questionChoice);
                }
                answer.setAnswer(stringBuilder.toString());
            }
        }
        questionAnswerMapper.insert(answer);
    }

    @Override
    public void updateQuestion(Question question) {
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        questionLambdaQueryWrapper.eq(Question::getTitle, question.getTitle());
        questionLambdaQueryWrapper.eq(Question::getCategoryId, question.getCategoryId());
        questionLambdaQueryWrapper.eq(Question::getType, question.getType());
        questionLambdaQueryWrapper.ne(Question::getId, question.getId());
        boolean b = baseMapper.exists(questionLambdaQueryWrapper);
        if (b) {
            //获取分类名
            Category category = categoryMapper.selectById(question.getCategoryId());
            //在某个分类下该类型的题目已经存在同名的题目
            throw new ExamException(678, "在<" + category.getName() + ">分类下已经存在名字为 '" + question.getTitle() + "' 的题目");
        }
        question.setUpdateTime(new Date());
        //1.调用自带的方法插入题目信息
        baseMapper.updateById(question);
        QuestionAnswer answer = question.getAnswer();
        answer.setUpdateTime(new Date());
        if (question.getType().equals("CHOICE")) {
            questionChoiceMapper.delete(new LambdaQueryWrapper<QuestionChoice>().eq(QuestionChoice::getQuestionId, question.getId()));
            List<QuestionChoice> choices = question.getChoices();
            if (!CollectionUtils.isEmpty(choices)) {
                // 按照sort属性排序选项
                choices.sort(Comparator.comparingInt(QuestionChoice::getSort));
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < choices.size(); i++) {
                    QuestionChoice questionChoice = choices.get(i);
                    questionChoice.setSort(i);
                    questionChoice.setQuestionId(question.getId());
                    //设置题目选项的id为null
                    questionChoice.setId(null);
                    //设置创建时间和更新时间为null
                    questionChoice.setCreateTime(null);
                    questionChoice.setUpdateTime(null);
                    if (questionChoice.getIsCorrect()) {
                        if (stringBuilder.length() > 0) {
                            stringBuilder.append(",");
                        }
                        stringBuilder.append((char) (i + 65));
                    }
                    questionChoiceMapper.insert(questionChoice);
                }
                answer.setAnswer(stringBuilder.toString());
            }
        }
        questionAnswerMapper.updateById(answer);
    }

    @Override
    public void deleteQuestionById(Long id) {
        LambdaQueryWrapper<PaperQuestion> paperQuestionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        paperQuestionLambdaQueryWrapper.eq(PaperQuestion::getQuestionId, id);
        Long l = paperQuestionMapper.selectCount(paperQuestionLambdaQueryWrapper);
        if (l > 0) {
            throw new ExamException(789, "该题目被试卷使用，不能删除");
        }
        baseMapper.deleteById(id);
        questionAnswerMapper.deleteById(id);
        questionChoiceMapper.delete(new LambdaQueryWrapper<QuestionChoice>().eq(QuestionChoice::getQuestionId, id));
    }

    @Override
    public List<Question> getPopularQuestions(Integer size) {
        ArrayList<Question> questions = new ArrayList<>();
        Set<Object> redisQuestionIds = new HashSet<>();
        try {
            redisQuestionIds = redisTemplate.opsForZSet().reverseRange("question:popular", 0, size - 1);
        } catch (Exception e) {
            // Redis连接失败，降级处理，直接从数据库获取最新题目
            log.warn("Redis连接失败，降级处理获取热门题目: {}", e.getMessage());
        }
        if (!CollectionUtils.isEmpty(redisQuestionIds)) {
            redisQuestionIds.forEach(object -> {
                Question question = baseMapper.selectById(object.toString());
                questions.add(question);
            });
        }
        int i = size - questions.size();
        if (i > 0) {
            LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            questionLambdaQueryWrapper.orderByDesc(Question::getCreateTime);
            if (!CollectionUtils.isEmpty(redisQuestionIds)) {
                questionLambdaQueryWrapper.notIn(Question::getId, redisQuestionIds);
            }
            questionLambdaQueryWrapper.last("limit " + i);
            List<Question> questionList = baseMapper.selectList(questionLambdaQueryWrapper);
            questions.addAll(questionList);
        }
        setAnswersAndChoice(questions);
        return questions;
    }

    @Override
    public List<QuestionImportVo> previewExcel(MultipartFile file) throws IOException {
        if (file == null || file.getSize() <= 0) {
            throw new ExamException(123, "文件不能为空");
        }
        if (!file.getOriginalFilename().endsWith(".xlsx") && !file.getOriginalFilename().endsWith(".xls")) {
            throw new ExamException(123, "文件格式错误");
        }
        return ExcelUtil.parseExcel(file);
    }

    @Override
    public List<QuestionImportVo> generateQuestionsByAi(AiGenerateRequestVo request) {
        String prompt = buildPrompt(request);
        String content = aiService.callAi(prompt);
        //3.解析结果
        int startIndex = content.indexOf("```json");
        int endIndex = content.lastIndexOf("```");
        String realResult;

        // 处理带代码块标记和不带代码块标记的情况
        if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
            //获取真正结果（去除代码块标记）
            realResult = content.substring(startIndex + 7, endIndex).trim();
        } else {
            // 如果没有代码块标记，使用整个内容作为JSON
            realResult = content.trim();
        }

        System.out.println("realResult = " + realResult);

        try {
            // 解析JSON并生成题目列表
            JSONObject jsonObject = JSONObject.parseObject(realResult);
            JSONArray questions = jsonObject.getJSONArray("questions");
            List<QuestionImportVo> questionImportVoList = new ArrayList<>();
            for (int i = 0; i < questions.size(); i++) {
                //获取对象
                JSONObject questionJson = questions.getJSONObject(i);
                QuestionImportVo questionImportVo = new QuestionImportVo();
                questionImportVo.setTitle(questionJson.getString("title"));
                questionImportVo.setType(questionJson.getString("type"));
                questionImportVo.setMulti(questionJson.getBoolean("multi"));
                questionImportVo.setDifficulty(questionJson.getString("difficulty"));
                questionImportVo.setScore(questionJson.getInteger("score"));
                questionImportVo.setAnalysis(questionJson.getString("analysis"));
                questionImportVo.setCategoryId(request.getCategoryId());

                //选择题处理选项
                if ("CHOICE".equals(questionImportVo.getType())) {
                    JSONArray choices = questionJson.getJSONArray("choices");
                    List<QuestionImportVo.ChoiceImportDto> choiceImportDtoList = new ArrayList<>(choices.size());
                    for (int i1 = 0; i1 < choices.size(); i1++) {
                        JSONObject choicesJSONObject = choices.getJSONObject(i1);
                        QuestionImportVo.ChoiceImportDto choiceImportDto = new QuestionImportVo.ChoiceImportDto();
                        choiceImportDto.setContent(choicesJSONObject.getString("content"));
                        choiceImportDto.setIsCorrect(choicesJSONObject.getBoolean("isCorrect"));
                        choiceImportDto.setSort(choicesJSONObject.getInteger("sort"));
                        choiceImportDtoList.add(choiceImportDto);
                    }
                    questionImportVo.setChoices(choiceImportDtoList);
                }
                //答案 [判断题！ TRUE |FALSE  false true  f  t 是 否]
                questionImportVo.setAnswer(questionJson.getString("answer"));
                questionImportVoList.add(questionImportVo);
            }
            return questionImportVoList;
        } catch (JSONException e) {
            // 处理JSON解析异常
            System.err.println("JSON解析错误：" + e.getMessage());
            System.err.println("解析的JSON数据：" + realResult);
            throw new RuntimeException("ai生成题目json数据结构错误，无法正常解析！数据为：%s".formatted(content));
        } catch (Exception e) {
            // 处理其他可能的异常
            System.err.println("处理JSON数据时发生错误：" + e.getMessage());
            System.err.println("解析的JSON数据：" + realResult);
            throw new RuntimeException("ai生成题目处理失败！", e);
        }
    }


    public String buildPrompt(AiGenerateRequestVo request) {
        StringBuilder prompt = new StringBuilder();

        prompt.append("请为我生成").append(request.getCount()).append("道关于【")
                .append(request.getTopic()).append("】的题目。\n\n");

        prompt.append("要求：\n");

        // 题目类型要求
        if (request.getTypes() != null && !request.getTypes().isEmpty()) {
            List<String> typeList = Arrays.asList(request.getTypes().split(","));
            prompt.append("- 题目类型：");
            for (String type : typeList) {
                switch (type.trim()) {
                    case "CHOICE":
                        prompt.append("选择题");
                        if (request.getIncludeMultiple() != null && request.getIncludeMultiple()) {
                            prompt.append("(包含单选和多选)");
                        }
                        prompt.append(" ");
                        break;
                    case "JUDGE":
                        prompt.append("判断题（**重要：确保正确答案和错误答案的数量大致平衡，不要全部都是正确或错误**） ");
                        break;
                    case "TEXT":
                        prompt.append("简答题 ");
                        break;
                }
            }
            prompt.append("\n");
        }

        // 难度要求
        if (request.getDifficulty() != null) {
            String difficultyText = switch (request.getDifficulty()) {
                case "EASY" -> "简单";
                case "MEDIUM" -> "中等";
                case "HARD" -> "困难";
                default -> "中等";
            };
            prompt.append("- 难度等级：").append(difficultyText).append("\n");
        }

        // 额外要求
        if (request.getRequirements() != null && !request.getRequirements().isEmpty()) {
            prompt.append("- 特殊要求：").append(request.getRequirements()).append("\n");
        }

        // 判断题特别要求
        if (request.getTypes() != null && request.getTypes().contains("JUDGE")) {
            prompt.append("- **判断题特别要求**：\n");
            prompt.append("  * 确保生成的判断题中，正确答案(TRUE)和错误答案(FALSE)的数量尽量平衡\n");
            prompt.append("  * 不要所有判断题都是正确的或都是错误的\n");
            prompt.append("  * 错误的陈述应该是常见的误解或容易混淆的概念\n");
            prompt.append("  * 正确的陈述应该是重要的基础知识点\n");
        }

        // 选择题特别要求
        if (request.getTypes() != null && request.getTypes().contains("CHOICE")) {
            prompt.append("- **选择题特别要求**：\n");
            prompt.append("  * 确保生成的选择题中有明确的正确答案\n");
            prompt.append("  * 选项内容应该具有干扰性，避免过于明显或荒谬的选项\n");
            prompt.append("  * 单选题应该只有一个正确答案，多选题可以有多个正确答案\n");
            prompt.append("  * 选项数量建议在2-4个之间，保持选项长度相对均衡\n");
            prompt.append("  * 题目应该覆盖不同的知识点，避免重复考查相同内容\n");
            prompt.append("  * 确保各选项作为正确答案的分布尽量均匀，避免大多数题目的正确答案都是同一选项\n");
            prompt.append("  * 正确答案应在A、B、C、D等选项中随机分布\n");
            prompt.append("  * 不要出现连续多题正确答案为同一选项的情况\n");
        }


        prompt.append("\n请严格按照以下JSON格式返回，不要包含任何其他文字：\n");
        prompt.append("```json\n");
        prompt.append("{\n");
        prompt.append("  \"questions\": [\n");
        prompt.append("    {\n");
        prompt.append("      \"title\": \"题目内容\",\n");
        prompt.append("      \"type\": \"CHOICE|JUDGE|TEXT\",\n");
        prompt.append("      \"multi\": true/false,\n");
        prompt.append("      \"difficulty\": \"EASY|MEDIUM|HARD\",\n");
        prompt.append("      \"score\": 5,\n");
        prompt.append("      \"choices\": [\n");
        prompt.append("        {\"content\": \"选项内容\", \"isCorrect\": true/false, \"sort\": 1}\n");
        prompt.append("      ],\n");
        prompt.append("      \"answer\": \"TRUE或FALSE(判断题专用)|文本答案(简答题专用)\",\n");
        prompt.append("      \"analysis\": \"题目解析\"\n");
        prompt.append("    }\n");
        prompt.append("  ]\n");
        prompt.append("}\n");
        prompt.append("```\n\n");

        prompt.append("注意：\n");
        prompt.append("1. 选择题必须有choices数组，判断题和简答题设置answer字段\n");
        prompt.append("2. 多选题的multi字段设为true，单选题设为false\n");
        prompt.append("3. **判断题的answer字段只能是\"TRUE\"或\"FALSE\"，请确保答案分布合理**\n");
        prompt.append("4. 每道题都要有详细的解析\n");
        prompt.append("5. 题目要有实际价值，贴近实际应用场景\n");
        prompt.append("6. 严格按照JSON格式返回，确保可以正确解析\n");

        // 如果只生成判断题，额外强调答案平衡
        if (request.getTypes() != null && request.getTypes().equals("JUDGE") && request.getCount() > 1) {
            prompt.append("7. **判断题答案分布要求**：在").append(request.getCount()).append("道判断题中，");
            int halfCount = request.getCount() / 2;
            if (request.getCount() % 2 == 0) {
                prompt.append("请生成").append(halfCount).append("道正确(TRUE)和").append(halfCount).append("道错误(FALSE)的题目");
            } else {
                prompt.append("请生成约").append(halfCount).append("-").append(halfCount + 1).append("道正确(TRUE)和约").append(halfCount).append("-").append(halfCount + 1).append("道错误(FALSE)的题目");
            }
        }

        return prompt.toString();
    }

    @Override
    public Integer importQuestions(List<QuestionImportVo> questions) {
        if (CollectionUtils.isEmpty(questions)) {
            throw new ExamException(123, "导入的题目不能为空");
        }
        Integer successCount = 0;
        for (int i = 0; i < questions.size(); i++) {
            QuestionImportVo questionImportVo = questions.get(i);
            Question question = getQuestionFromImportVo(questionImportVo);
            addQuestion(question);
            successCount++;
        }
        return successCount;
    }

    private Question getQuestionFromImportVo(QuestionImportVo questionImportVo) {
        Question question = new Question();
        BeanUtils.copyProperties(questionImportVo, question);
        QuestionAnswer questionAnswer = new QuestionAnswer();
        //设置答案，判断题的答案必须大写所以单拿出来赋值
        if (questionImportVo.getType().equals("JUDGE")) {
            questionAnswer.setAnswer(questionImportVo.getAnswer().toUpperCase());
        } else {
            questionAnswer.setAnswer(questionImportVo.getAnswer());
        }
        questionAnswer.setKeywords(questionImportVo.getKeywords());
        //补全question的属性，因为需要返回，之后会被addquestion方法使用，其中就要question中的所有属性来进行往数据库添加信息
        question.setAnswer(questionAnswer);

        if (questionImportVo.getType().equals("CHOICE")) {
            List<QuestionImportVo.ChoiceImportDto> choices = questionImportVo.getChoices();
            List<QuestionChoice> questionChoices = new ArrayList<>();
            if (!CollectionUtils.isEmpty(choices)) {
                choices.forEach(choice -> {
                    QuestionChoice questionChoice = new QuestionChoice();
                    BeanUtils.copyProperties(choice, questionChoice);
                    questionChoices.add(questionChoice);
                });
            }
            question.setChoices(questionChoices);
        }

        return question;
    }

}